import { SET_TODO_LIST } from './../../store/actionTypes'
import { Store, useStore } from 'vuex'
import { ITodo, TODO_STATUS } from '../../typings'

interface IUseTodo {
  setTodo: (value: string) => void
  setTodoList: () => void
  removeTodo: () => void
  setDoing: () => void
  setStatus: () => void
}

interface IUseLocalList {
  getLocalList: () => ITodo[]
  setLocalList: (list: ITodo[]) => void
}
function useTodo(): IUseTodo {
  const store: Store<any> = useStore()
  const { getLocalList, setLocalList }: IUseLocalList = useLocalStorage()
  const todoList: ITodo[] = getLocalList()
  const setTodo = (value: string): void => {
    const todo: ITodo = {
      id: new Date().getTime(),
      content: value,
      status: TODO_STATUS.WILLDO,
    }
    store.dispatch('SET_TODO', todo)
    setLocalList(store.state.list)
  }
  const setTodoList = () => {
    store.dispatch('SET_TODO_LIST', todoList)
  }
  const removeTodo = () => {}
  const setDoing = () => {}
  const setStatus = () => {}
  return {
    setTodo,
    setTodoList,
    removeTodo,
    setDoing,
    setStatus,
  }
}

function useLocalStorage(): IUseLocalList {
  const getLocalList = (): ITodo[] => {
    return localStorage['todoList'] ? JSON.parse(localStorage['todoList']) : []
  }
  const setLocalList = (list: ITodo[]): void => {
    localStorage['todoList'] = JSON.stringify(list)
  }
  return {
    getLocalList,
    setLocalList,
  }
}

export { useTodo, IUseTodo, useLocalStorage, IUseLocalList }
